package cn.kicsy.www.anonymous_bbs.service;

import cn.kicsy.www.anonymous_bbs.entity.Post;
import cn.kicsy.www.anonymous_bbs.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class PostService {
    
    @Autowired
    private PostRepository postRepository;
    
    @Autowired
    private RandomNicknameService randomNicknameService;
    
    @Autowired
    private SensitiveWordFilterService sensitiveWordFilterService;
    
    @Autowired
    private BanService banService;
    
    @Autowired
    private NotificationService notificationService;
    
    @Autowired
    private IpLocationService ipLocationService;
    
    /**
     * 创建新帖子
     * @param content 帖子内容
     * @param ipAddress 用户IP地址
     * @return 创建的帖子
     */
    public Post createPost(String content, String ipAddress) {
        // 检查用户是否被封禁
        if (banService.isBanned(ipAddress)) {
            throw new RuntimeException("您已被封禁，无法发布帖子。原因：" + banService.getBanReason(ipAddress));
        }
        
        // 检查内容是否为空
        if (content == null || content.trim().isEmpty()) {
            throw new RuntimeException("帖子内容不能为空");
        }
        
        // 检查内容长度是否合理
        if (content.length() > 10000) {
            throw new RuntimeException("帖子内容不能超过10000字符");
        }
        
        // 创建帖子对象
        Post post = new Post();
        post.setAuthorName(randomNicknameService.generateRandomNickname());
        post.setContent(content);
        post.setIpAddress(ipAddress);
        
        // 设置IP地理位置
        String location = ipLocationService.getLocation(ipAddress);
        post.setLocation(location);
        
        // 检查并标记敏感词
        if (sensitiveWordFilterService.containsSensitiveWords(content)) {
            post.setHasSensitiveWords(true);
            // 可以在这里触发通知，提醒管理员有敏感内容
        }
        
        // 保存帖子
        return postRepository.save(post);
    }
    
    /**
     * 获取帖子列表（按创建时间降序）
     * @return 帖子列表
     */
    public List<Post> getPostList() {
        return postRepository.findAllByOrderByCreatedAtDesc();
    }
    
    /**
     * 根据ID获取帖子详情
     * @param postId 帖子ID
     * @return 帖子详情，如果不存在则返回null
     */
    public Post getPostById(Long postId) {
        Optional<Post> optionalPost = postRepository.findById(postId);
        if (optionalPost.isPresent()) {
            Post post = optionalPost.get();
            // 增加浏览次数
            post.setViewCount(post.getViewCount() + 1);
            postRepository.save(post);
            return post;
        }
        return null;
    }
    
    /**
     * 点赞帖子
     * @param postId 帖子ID
     * @param ipAddress 用户IP地址
     * @return 点赞后的点赞数
     */
    public int likePost(Long postId, String ipAddress) {
        // 检查用户是否被封禁
        if (banService.isBanned(ipAddress)) {
            throw new RuntimeException("您已被封禁，无法点赞");
        }
        
        Optional<Post> optionalPost = postRepository.findById(postId);
        if (optionalPost.isPresent()) {
            Post post = optionalPost.get();
            post.setLikeCount(post.getLikeCount() + 1);
            post = postRepository.save(post);
            
            // 如果点赞的不是自己的帖子，可以发送通知
            if (!ipAddress.equals(post.getIpAddress())) {
                notificationService.createNotification(
                    post.getIpAddress(),
                    "post_liked",
                    "您的帖子收到了一个点赞",
                    postId,
                    null
                );
            }
            
            return post.getLikeCount();
        }
        throw new RuntimeException("帖子不存在");
    }
}